package com.ljs.module.controller;

import com.ljs.module.common.DataBean;
import com.ljs.module.common.PathEnum;
import com.ljs.module.entity.template.custom.Custom;
import com.ljs.module.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;

@Controller
@RequestMapping("/template/custom")
public class BuildCustomTemplateController {

    @ResponseBody
    @GetMapping("/extend/json")
    public DataBean<String> getExtendJson(String path, String name){
        try {
            File file = new File(PathEnum.TEMPLATE + File.separator + path + File.separator + name);
            if (!file.exists()) {
                return DataBean.success("{}");
            }
            String content = FileUtil.readFile2Content(file.getAbsolutePath());
            return DataBean.success(content);
        } catch (Exception ex) {
            return DataBean.success("{}");
        }
    }

    @ResponseBody
    @PostMapping("/build")
    public DataBean<String> buildTemplate(@RequestBody Custom custom){
        try {
            return DataBean.success(custom.build());
        } catch (Exception ex) {
            return DataBean.fail("未知错误" + ex.getMessage());
        }
    }
}
